from flask import Flask, session, g
import config
from models import UserModel
from exts import db, mail
from blueprints.qa import blueprints as qa_bp
from blueprints.auth import blueprints as auth_bp
from blueprints.user import blueprints as user_bp
from flask_migrate import Migrate

app = Flask(__name__)

# 绑定配置文件
app.config.from_object(config)

app.secret_key = 'CSaSvOU6h1iMb15s+GsV5TuKYSbREcBZ/g1Gjh9nCec='
# 设置session的过期时间
# app.config['PERMANENT_SESSION_LIFETIME'] = 1

# 初始化数据库,邮箱
db.init_app(app)
mail.init_app(app)
# 初始化迁移器
migrate = Migrate(app, db)
# 注册蓝图
app.register_blueprint(qa_bp)
app.register_blueprint(auth_bp)
app.register_blueprint(user_bp)


# hook 钩子函数
@app.before_request
def before_request():  # 每次请求之前都会执行
    user_id = session.get('user_id')
    if user_id:
        user = UserModel.query.get(user_id)
        setattr(g, 'current_user', user)
    else:
        setattr(g, 'current_user', None)


@app.context_processor
def context_processor():
    return {
        'current_user': g.current_user
    }


if __name__ == '__main__':
    app.run()
